<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Controller;
use think\Db;

/**
 * 示例接口
 */
class Jssdk extends Api
{
    //获取配置
    public function getconf(){
        $jsapiTicket = $this->getJsApiTicket();
        //不对url进行过滤
        $url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $timestamp = time();
        $nonceStr = $this->createNonceStr();
        // // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr & timestamp=$timestamp&url=$url";
        $signature = sha1($string);
        $signpackage = array(
            "appId"     => config('site.appid'),
            "nonceStr"  => $nonceStr,
            "timestamp" => $timestamp,
            "url"       => $url,
            "signature" => $signature,
            "rawString" => $string
        );
        echo json_encode($signpackage);
    }
//获取jsapiTicket
    private function getJsApiTicket() {
        $data = Db::name('weixin_token')
            ->where('type','jsapi_ticket')
            ->find();
        if($data['expire_time'] < time()){
            //       //如果数据库内令牌已失效 令牌有效期
            $accessToken = $this->getAccessToken();
            // print_r($accessToken);
            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
            $res = $this->httpGet($url);
            $res = json_decode($res);


            if(!empty($res->errcode)){
                $res->remarks = 'api_ticket获取失败';
                die(json_encode($res));
            }


            if ($res->ticket) {
                Db::name('weixin_token')
                    ->where('type','jsapi_ticket')
                    ->update([
                        'expire_time'=> time()+7000,
                        'code'=>$res->ticket
                    ]);
            }
            return $res->ticket;
        }
        return $data['code'];
    }
    //获取AccessToken
    private function getAccessToken() {
        // access_token 应该全局存储与更新，以下代码以写入到文件中做示例
        $data = Db::name('weixin_token')
            ->where('type','access_token')
            ->find();
        // print_r($data);
        $appid = config('site.appid');
        $appsecret = config('site.appsecret');
        if($data['expire_time']<time()){
            //如果数据库内Token过期
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appsecret}";
            $res = json_decode($this->httpGet($url));
            //如果接口错误
            if(!empty($res->errcode)){
                $res->remarks = 'accessToken获取失败';
                die(json_encode($res));
            }
            //更新数据库内token
            if ($res->access_token) {
                Db::name('weixin_token')
                    ->where('type','access_token')
                    ->update([
                        'expire_time'=> time()+7000,
                        'code'=>$res->access_token
                    ]);
            }
            return $res->access_token;
        }
        return $data['code'];
    }
    //创建随机字符
    private function createNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }
    //http获取
    private function httpGet($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }

}
